<?php
/**
 * 
 * 商品订单
 * 注:detail ajxDetail 两个方法是否均需要？
 * 		即：订单生成成功后，显示单独的订单支付界面，还是连接到用户发送订单界面来显示？
 * @author kim007
 *
 */
class orderAction extends BaseAction{
	
	public function _initialize() {
		parent::_initialize();
		$plugininfo = $_SESSION["plugininfo"];
		$plugin_bindmobile = $plugininfo["bindmobile"];
		$this->assign('plugin_bindmobile',$plugin_bindmobile);
		//echo $plugin_bindmobile.'--'.session_id();
	}

	public function _after_order(){
		//echo "do _after_action<br>";
	} 
	
	
	public function search(){
		$this->display();
	}
	
	public function sendList(){
		$this->display();
	}
	
	public function ajxSendList(){
		$this->display('list_box');
	}
	
	
	/*
	 *	编辑订单
	 */
	public function orderEdit(){
		
		$shelfid	= $_REQUEST['shelfid'];//上架ID。
		if(empty($shelfid))$this->error('查看的商品不存在！');
		/*　上架商品数据　*/
		$pservice 		= service('Product');
		$productdata	= $pservice->getByShelfId($shelfid);
		if(empty($productdata))$this->error('查看的商品不存在！');
		$checkresult = $pservice->checkProductStatus($productdata);
		if(	$checkresult['p_status']=='E' || $checkresult['g_status']=='E'
				||	$checkresult['s_status']=='E')$this->error('查看的商品不存在！');
		
		if(!$checkresult['isCanOn'])$this->error($productdata['goods_title'].' '.$checkresult['desc']);
		
		/* 页面导航条用到的数据 */
		$pcodes = service('Dict')->findAllParents($productdata['goods_sort_id']);
		$tmp = '';
		foreach($pcodes as $vo){
			if($vo['pid']!=0){
				$tmp = $tmp.'s';
				$nav_code[$tmp]=array('id' => $vo['code'],'desc' => $vo['desc']);
			}
		}
		$nav_code['p']=array('id' => $productdata['shelf_id'],'desc' => $productdata['goods_title']);
		
		$this->assign('productdata', $productdata);
		$this->assign('checkresult', $checkresult);
		$this->assign('nav_code', $nav_code);
		
		$this->display();
	}
	
	/*
	 *	确认订单
	*/
	public function confirm(){
		$shelf_id		= $_REQUEST['shelf_id'];			//上架ID。
		$receiver_no	= intval($_REQUEST['receiver_no']);		//接收者总数
		$receiver_data	= $_REQUEST['receiver_data'];	//接收者数据
		$sender_name	= $_REQUEST['sender_name'];		//送礼者名称
		$sender_mobile	= $_REQUEST['sender_mobile'];	//送礼者电话号码
		$send_format	= $_REQUEST['send_format'];		//sms=短信发送  mms=彩信发送
		$txt_content	= $_REQUEST['txt_content'];		//短信内容。
		$smsdata		= $_REQUEST['smsdata'];		//短信内容。
		$cardcontent	= $_REQUEST['cardcontent'];		//短信内容。
		//echo $smsdata;
		//echo $cardcontent;
		//参数合法性检查，验证不能为空项
		$required_field = array(
				'shelf_id'			=> '商品',
				'receiver_no'		=> '收礼人',
				'receiver_data'	=> '收礼人',
				'sender_name'		=> '送礼人名称',
				'sender_mobile'		=> '送礼人手机号码',
				'send_format'		=> '发送方式',
			);
		foreach ($required_field as $k => $v) {
			if ( empty($_POST[$k]) ) $this->error($v . '不可为空');
		}
		/** 验证收礼人总数与收礼数据总数是否相同 **/
		$receiver_data	= explode(':', $receiver_data);
		if(count($receiver_data)!=$receiver_no)$this->error('收礼人数据不正确！');

		/** 验证及获取上架商品信息 **/
		$pservice 		= service('Product');
		$productdata	= $pservice->getByShelfId($shelf_id);
		if(empty($productdata))$this->error('查看的商品不存在！');
		$checkresult = $pservice->checkProductStatus($productdata);
		if(	$checkresult['p_status']=='E' || $checkresult['g_status']=='E'
				||	$checkresult['s_status']=='E')$this->error('查看的商品不存在！');
		/** 判断商品是否上架 **/
		if(!$checkresult['isCanOn'])$this->error($checkresult['desc']);
		$order_data['shelf'] = $productdata;
			
		/** 验证收礼人数据是否正确（每条四个数据是否正确） **/
		$now_ = date( 'Y-m-d',time() );
		$shelf_off_time_ 		= date( 'Y-m-d',$productdata['shelf_off_time']);
		$remain_number_			= intval($productdata['stat_total_number'])-intval($productdata['stat_send_number']);
		$send_total_number_	=	0;
		foreach($receiver_data as $vol){
			$tmp_data_	= explode(',', $vol);
			if(count($tmp_data_)!=4)$this->error('收礼人数据不正确！');
			if(!isValidMobile($tmp_data_[0]))$this->error('收礼人电话号码错误！');
			if(intval($tmp_data_[1])<1||intval($tmp_data_[1])>30)$this->error('礼物数量输入不正确(1-10之间)！');
			if($now_ > $tmp_data_[2] || $shelf_off_time_ <= $tmp_data_[2])
					$this->error("发送时间需在 {$now_} 与 {$shelf_off_time_} 之间！");
				$receivers[]=$tmp_data_;
				$send_total_number_ = $send_total_number_ + intval($tmp_data_[1]);
		}
		if($send_total_number_>$remain_number_)$this->error('剩余礼品数量不够！');
		$order_data['receivers']['data'] = $receivers;
		$order_data['receivers']['send_total_no'] = $send_total_number_;
			
		/** 验证送礼人信息 **/
		/** 验证发送方式参数是否正确    将彩信屏蔽掉，只支持短信发送 **/
		//if(!in_array($send_format,array('mms','sms'))) $this->error('请选择发送方式！');
		if(!in_array($send_format,array('sms'))) $this->error('请选择发送方式！');
		
		if( !isValidMobile($sender_mobile) ) $this->error('送礼人电话号码不正确！');
		//if( strlen($sender_name)>6 ) $this->error('送礼人名称6字符内！');
		$sender['send_format']		=	$send_format;
		$sender['sender_mobile']	=	$sender_mobile;
		$sender['sender_name']		=	$sender_name;
		$order_data['sender'] = $sender;
			
		$smsdata = str_replace('\\"',"\"",$smsdata);
		$smsdata = json_decode($smsdata);
		$smsdata[0]->smstext=$cardcontent;
		//dump($smsdata);
		$order_data['smsdata'] = $smsdata[0];
		$order_data['txtdata']['txt_content'] = $txt_content;
		
		/** 支付相关 **/
		$order_data['payment']['total_price'] 	= $order_data['receivers']['send_total_no']*$order_data['shelf']['shelf_out_price'];
		$order_data['payment']['gain_credit'] 	= $order_data['receivers']['send_total_no']*$order_data['shelf']['shelf_gain_credit'];
		$order_data['payment']['used_credit'] 	= $order_data['receivers']['send_total_no']*$order_data['shelf']['shelf_gain_credit'];
		$order_data['payment']['out_price'] 	= $order_data['shelf']['shelf_out_price'];
		$order_data['payment']['total_no'] 		= $order_data['receivers']['send_total_no'];
		$order_data['payment']['pay_money'] 	= $order_data['payment']['total_price']-($order_data['payment']['used_credit']/100);
		$order_data['payment']['total_price'] 	= sprintf("%01.2f", $order_data['payment']['total_price']);
		$order_data['payment']['pay_money'] 	= sprintf("%01.2f", $order_data['payment']['pay_money']);
			
		/** 截止日期 **/
		//echo date("Y-m-d",strtotime("5 month",strtotime("2003-3-4")));
		//echo date("Y-m-d",strtotime("5 month",strtotime("2003-1-31"))).'<br>';
		unset($_SESSION['order_data']);
		$_SESSION['order_data'] = $order_data;
		//dump(getSubByKey($order_data['receivers']['data'],0));
		$mobilenames = model('User')->selectPhoneBook4KeyValue(
												array(	
														'ownerid'=>$_SESSION['mid']
														,'is_delete'=>'N'
														,'mobile'=>array('in',getSubByKey($order_data['receivers']['data'],0))
													 )
												);
		$this->assign('mobilenames', $mobilenames);
		//dump($mobilenames);
		$this->assign('productdata', $productdata);
		$this->assign('order_data', $order_data);
		///dump($order_data);
		$this->display();
	}
	
	
	/** 获取彩信图片数据 **/
	function getSmsImg(){
		$smsdata 	= $_SESSION['order_data']['smsdata'];
		$smsimg 	= $smsdata->smsimg;
     	$smstext 	= $smsdata->smstext;
     	$xyOffset 	= $smsdata->xyOffset;
     	$textcolor 	= $smsdata->textcolor;
     	$smsicon 	= $smsdata->smsicon;//表情图片路径
		//dump($_SESSION['order_data']['smsdata']);
     	$smsImgDao = service('SmsImg');
     	$imgdata_ = $smsImgDao->parseRequestData($xyOffset,$textcolor,$font_file,$font_size);
     	$im = $smsImgDao->writeTxtImg2Bg(SITE_PATH.getAttachUrl($smsimg),SITE_PATH.$smsicon
     															,$smstext,$imgdata_['xyOffset'],$imgdata_['rgb']
																,$imgdata_['font_file'],$imgdata_['font_size']);
		
		Header ('Content-type: image/png');//即便是从jpg拷贝的图片，也能以png输出，  
		ImagePng ($im);  
		// clean up  
		ImageDestroy($im);   
		exit;
	}
	
	
	/**提交订单
	 * ajax提交订单，确认生成订单。返回操作结果和订单id
	 */
	function doConfirm(){
		$result['status'] 	= -1;
		$result['msg'] 		= '数据有误！';
		$submit 	= $_POST['submit'];//为yes表示确认提交订单
		$order_data = $_SESSION['order_data'];
		if(empty($order_data)){
			$result['msg'] = '未选择商品！';
			exit(json_encode($result));
		}
		if($submit=='yes'){
			$id = service('Order')->do4UserSubmitOrder($_SESSION['order_data']);
			if(!empty($id)){
				$result['status'] = 1;
				$result['msg'] = '订单提交成功！';
				$result['order_id'] = $id;
				unset($_SESSION['order_data']);
				
				exit(json_encode($result));
			}else{
				$result['status'] = 0;
				$result['msg'] = '订单提交失败！';
				exit(json_encode($result));
			}
		}else{
			exit(json_encode($result));
		}
	}
	
	function doPay(){
		//$shelf_id		= $_REQUEST['shelf_id'];
		$order_id		= $_REQUEST['order_id'];
		$paytype		= $_REQUEST['paytype'];
		$order = service('Order')->get4UserById($order_id);
		if(empty($order))$this->error('订单不存在！');
		$productdata	= service('Product')->getByShelfId($order['shelf_id']);
		if(empty($productdata))$this->error('查看的商品不存在！');
		$this->assign('productdata', $productdata);
		$this->assign('order_id', $order_id);
		$this->assign('paytype', $paytype);
		$this->display();
	}

	
	/** 订单详情，并包含支付界面（未支付的订单） **/
	function ajxDetail(){
		$order_id	=	$_REQUEST['order_id'];
		$paytype	=	$_REQUEST['paytype'];
		
		$this->assign('order_id'		, $order_id);
		$this->assign('paytype'		, $paytype);
		$this->display('detail_box');
	}
	
	/** 查看发送的礼物，短信/彩信内容
	 * **/
  	public function giftSendInfo(){
  		$order_id = $_REQUEST['order_id'];
  		Log::record('OrderAction.giftSendInfo()发送者查询发送的短信信息。order_id='.$order_id,Log::DEBUG,Log::FILE);
  		$orderInfo 	= service('Order')->get4SysById($order_id);
  		Log::record('OrderAction.giftSendInfo()发送者查询发送的短信信息。order_id='.$order_id.',对应订单数据='.parseAry2Str($orderInfo),Log::DEBUG,Log::FILE);
		if(!empty($orderInfo))$productdata	= service('Product')->getByShelfId($orderInfo['shelf_id']);
		Log::record('OrderAction.giftSendInfo()发送者查询发送的短信信息。order_id='.$order_id.',对应商品数据='.parseAry2Str($productdata),Log::DEBUG,Log::FILE);
		if(!empty($orderInfo)){
			$coupons = service('Coupon')->select4UserByOrderId($order_id);
			if(!empty($coupons))$coupon = $coupons[0];
		}
		Log::record('OrderAction.giftSendInfo()发送者查询发送的短信信息。order_id='.$order_id.',对应礼券数据='.parseAry2Str($coupon),Log::DEBUG,Log::FILE);
		$this->assign('coupon', $coupon);
		$this->assign('productdata', $productdata);
		$this->assign('orderInfo', $orderInfo);
		Log::save(); 
  		$this->display();
  	}
  	
  	/**
  	 * 检查优惠券
  	 */
  	public function ajxCheckCashCoupon(){
  		$ccpcode = $_POST['ccpcode'];
  		if(empty($ccpcode))$this->error('优惠券码错误！');
  		$order_data = $_SESSION['order_data'];
  		$ruledata['goods_id'] = $order_data['shelf']['goods_id'];
  		$ruledata['partner_id'] = $order_data['shelf']['partner_id'];
  		$ruledata['amount'] = $order_data['payment']['total_price'];
  		$result=service('CashCoupon')->doCheck($ccpcode,$ruledata);
  		//$result['msg']=$result['msg'].$ruledata['amount'];
		exit(json_encode($result));
  	}
  	
  	
  	/**
  	 * 确认使用优惠券
  	 */
	public function ajxUseCashCoupon(){
  		$ccpcode = $_POST['ccpcode'];
  		if(empty($ccpcode))$this->error('优惠券码错误！');
  		$order_data = $_SESSION['order_data'];
  		$ruledata['goods_id'] = $order_data['shelf']['goods_id'];
  		$ruledata['partner_id'] = $order_data['shelf']['partner_id'];
  		$ruledata['amount'] = $order_data['payment']['total_price'];
  		$result=service('CashCoupon')->doCheck($ccpcode,$ruledata);
  		if($result['status']==1){$_SESSION['order_data']['cashcoupon']=$result['data'];$result['msg']="使用成功！";}
		exit(json_encode($result));
  	}
  	
	/**
  	 * 取消使用优惠券，未确认订单前。
  	 */
	public function ajxCancelCashCoupon(){
  		$_SESSION['order_data']['cashcoupon']=null;
  		$result['status']=1;
  		$result['msg']="取消成功！";
		exit(json_encode($result));
  	}
  	
  	
/**
     * 用户绑定手机。
     * 规则：绑定手机将接触已绑定的手机号。
     * 		一个手机可绑定多个账户。
     * 		先录入手机号码，然后录入验证码进行验证才可绑定。
     */
    function bindMobile(){
    	$mobile = 	t($_POST['mobile']);
    	$verify =	$_POST['verify']; 
    	if(empty($mobile))$this->error('请录入手机号码！');
    	if(!isValidMobile($mobile))$this->error('请输入正确的手机号码！');
    	if(empty($verify))$this->error('请录入验证码！');
    	$bmobile  		= $_SESSION['usertempdata']['bmobile']; 	//要验证的手机
    	$bmverify 		= $_SESSION['usertempdata']['bmverify'];	//发送的临时验证码
    	$errorno  		= intval($_SESSION['usertempdata']['errorno']); 	//验证码输入错误次数
    	$bmvsendtime 	= $_SESSION['usertempdata']['bmvsendtime'];	//验证码发送时间
    	if(empty($bmobile)||empty($bmverify)||empty($bmvsendtime))$this->error('请获取验证码！');
    	Log::record('手机绑定：['.$mobile.']['.$verify.']['.md5($verify).']['.$bmobile.']['.$bmverify.']['.$bmvsendtime.']',Log::DEBUG,Log::FILE);	
    	if(empty($bmobile)||empty($bmverify)||empty($bmvsendtime))$this->error('请获取验证码！');
		Log::save();
		if(empty($bmverify))$this->error('请先获取验证码！');
		if($errorno>3){
			$this->error('验证码录入错误已超过三次，一小时内不能进行绑定操作！');
			exit;
		}
    	if (md5($verify)==$bmverify&&$mobile==$bmobile) {
    		
	    	//如果已发送验证码，并且发送时间已过一小时，则需重新获取验证码。
	    	if( !empty($bmvsendtime) && time()-intval($bmvsendtime)>60*60 ){
	    		$this->_unsetUsertempdata();
	    		$this->error('验证码失效，请重新获取！');
	    		exit;
	    	}
    		
			$_SESSION['plugininfo']['bindmobile']=$bmobile;
			//echo "dobind=".$mobile;

			$this->_unsetUsertempdata();
			$this->success('验证手机 [ '.$mobile.' ] 成功 ！');
			
		}else{
			$_SESSION['usertempdata']['errorno']=intval($errorno)+1;
			$this->error('验证码错误 （'.($errorno+1).'）！');
		}
		
    }
 
	private function _unsetUsertempdata(){
    	$_SESSION['usertempdata']['bmobile']	=	'';
    	$_SESSION['usertempdata']['bmverify']	=	'';
    	$_SESSION['usertempdata']['bmvsendtime']=	0;
    	$_SESSION['usertempdata']['errorno']	=	0;
    }
    
    function unBindMobile(){
    	$_SESSION['plugininfo']['bindmobile']=null;
		$this->success('取消手机绑定成功 ！');
    }
    
    
    /**
     * 获得绑定手机验证码。
     * 每次执行改该操作的间隔时间为一小时。
     * 判断规则为：验证法下发时间。
     */
    function sendBMVerifyCode(){
    	$mobile = 	t($_POST['mobile']);
    	if(empty($mobile))$this->error('请录入手机号码！');
    	if(!isValidMobile($mobile))$this->error('请输入正确的手机号码！');
    	//unset($_SESSION['usertempdata']['bmvsendtime']);
    	$bmvsendtime 	= $_SESSION['usertempdata']['bmvsendtime'];
    	$bmvsendtime	= intval($bmvsendtime);
    	//如果已发送验证码，并且发送时间还未过一小时，则不能再次发送。
    	if( !empty($_SESSION['usertempdata']['bmverify']) && (time()-$bmvsendtime)<60*60 )
    		$this->error('验证码已发送，请等待。一小时内不能再次发送！');
    	
    	//生成六位随机数
    	include_once( QUICK_ADDONE_PATH.'/libs/String.class.php' );
    	$randval = String::rand_string(6,1);
    	
    	$ary_mobiles[]	=$mobile;
    	$content 		= "来自小心意：手机绑定验证码：".$randval."[小心意网]";
    	$result	= service('SendCenter')->sendSms($ary_mobiles,$content);
   
    	if($result['status']==1){
    		//验证码发送成功
    		$_SESSION['usertempdata']['bmobile']	=	$mobile;
    		$_SESSION['usertempdata']['bmverify']	=	md5($randval);
    		$_SESSION['usertempdata']['bmvsendtime']=	time();
    		$_SESSION['usertempdata']['errorno']	=	0;
    		Log::record('手机绑定验证码：['.$randval.']',Log::DEBUG,Log::FILE);	
			Log::save();
    		$this->success('请录入收到的验证码，进行手机绑定！');
    	}else{
    		$this->error('发送错误，请稍后再试！');
    	}
    }
  	
}
?>